import React, { useEffect, useState, useMemo } from "react";
import { useLocation, Navigate } from "react-router-dom";
import store from "@/store";

export function withUser(InnerComponent) {
    return function OuterComponent(props) {
        const { userInfo } = store.getState();

        return <InnerComponent {...props} user={userInfo}></InnerComponent>;
    };
}

export function withStore(mapStateToProps) {
    return function (InnerComponent) {
        return function OuterComponent(props) {
            let [userState, setUserState] = useState({});
            useEffect(() => {
                const state = store.getState();
                let newUserState;
                try {
                    newUserState = mapStateToProps(state);
                } catch (err) {
                    newUserState = {};
                }

                setUserState(newUserState);

                store.subscribe(() => {
                    const state = store.getState();
                    let newUserState;
                    try {
                        newUserState = mapStateToProps(state);
                    } catch (err) {
                        newUserState = {};
                    }

                    setUserState(newUserState);
                });
            }, []);

            return <InnerComponent {...props} {...userState}></InnerComponent>;
        };
    };
}

/**
 * 用户登录才能访问组件
 * @param {Component} InnerComponent
 * @returns
 */
export function withLogin(InnerComponent) {
    return function WrapperComponent(props) {
        const { userInfo } = store.getState();
        const isLogin = useMemo(() => !!userInfo.authorization, [userInfo]);

        const { pathname: targetUrl } = useLocation();

        return isLogin ? <InnerComponent {...props} /> : <Navigate to={"/login?target=" + targetUrl} />;
    };
}
